<?php

namespace blog\admin\controller;

use think\Controller;
use think\Db;

class Type extends Controller
{
    public function _initialize()
    {
        check_login();
    }

    //添加和修改通用模板渲染
    private function _opFetch($txt, $data_id)
    {
        $this->assign('optxt', $txt);
        $this->assign('parent', session($data_id.".typename"));
        $this->assign('url', url('', 'data_id='.$data_id));
        return view('add');
    }

    //添加类型提交操作
    public function add($data_id = "datalist")
    {
        if ($this->request->isPost()) {
            $pid = session($data_id.'.pid') ?? false;
            if ($pid === false)
                return json_return('非法操作!');

            $sort = sqlCol('select max(sort) from bg_type where pid='.$pid) ?? 0;
            if ($pid === 0)
                $path = ',,';
            $path = sqlCol('select path from bg_type where id='.$pid);
            $path = $path === ',,' ? ','.$pid.',' : $path.$pid.',';

            $ret = Db::table('bg_type')->insert([
                'tag' => $_POST['tag'],
                'pid' => $pid,
                'name' => $_POST['name'],
                'path' => $path,
                'sort' => ++$sort
            ]);

            return $ret ? json_return_refresh('操作成功!', $data_id)
                        : json_return('操作失败!');
        }

        return $this->_opFetch('添加', $data_id);
    }

    //编辑类型提交操作
    public function edit($data_id = null, $id = null)
    {
        if ($this->request->isPost()) {
            if (!isset($_POST['update_id'])
                    || $_POST['update_id'] === '') {
                return json_return('非法操作!');
            }

            $ret = Db::table('bg_type')->where('id', $_POST['update_id'])
                ->update([
                'tag' => $_POST['tag'],
                'name' => $_POST['name'],
                'mtime' => date('Y-m-d H:i:s')
            ]);

            return $ret ? json_return_refresh('操作成功!', $data_id)
                        : json_return('操作失败!');
        }

        if ($data_id === null || $id === null)
            return json_return('非法操作!');

        $this->assign('row', sqlRow('select * from bg_type where id='.$id));
        return $this->_opFetch('编辑', $data_id);
    }

    //删除类型提交操作
    public function del($data_id, $id)
    {
        $count = sqlCol('select count(*) from bg_type where pid='.$id);
        if ($count)
            return json_return('此类型有子类型，请先删除所有子类型!');

        $ret = Db::table('bg_type')->delete($id);
        if ($ret == 0)
            return json_return('删除失败!');
        return json_return_refresh('删除成功!', $data_id, false);
    }

    public function move($data_id, $id, $move)
    {
        $curRow = sqlRow("select sort,pid from bg_type where id=".$id);
        if ($curRow === false)
            return json_return('非法操作');

        switch ($move) {
            case "bottom":
                $sort = sqlCol('select max(sort) from bg_type where pid='.$curRow['pid']) + 1;
                if ($sort === false)
                    return json_return('非法操作');
                $sql = 'update bg_type set sort='.$sort.' where id='.$id;
                $txt = "置尾";
                break;
            case 'top':
                $sql = 'update bg_type set stick=1 where id='.$id;
                $txt = "置顶";
                break;
            case 'ntop':
                $sql = 'update bg_type set stick=0 where id='.$id;
                $txt = "取消置顶";
                break;
            case 'up':
                $txt = "上移";
                $sql = 'select id,sort from bg_type where';
                $sql .= ' pid='.$curRow['pid'].' and ';
                $sql .= ' sort < '.$curRow['sort'];
                $sql .= ' order by sort desc limit 1';
                $swapRow = sqlRow($sql);
                if ($swapRow === false)
                    return json_return("此记录已经是第一条!");

                $sql = 'update bg_type set sort='.$curRow['sort'];
                $sql .= ' where id='.$swapRow['id'];
                $sql = Db::execute($sql);
                if (!$sql)
                    break;
                $sql = 'update bg_type set sort='.$swapRow['sort'];
                $sql .= ' where id='.$id;
                break;
            case 'down':
                $txt = "下移";
                $sql = 'select id,sort from bg_type where';
                $sql .= ' pid='.$curRow['pid'].' and ';
                $sql .= ' sort > '.$curRow['sort'];
                $sql .= ' order by sort limit 1';
                $swapRow = sqlRow($sql);
                if ($swapRow === false)
                    return json_return('此记录已经是最后一条!');

                $sql = 'update bg_type set sort='.$curRow['sort'];
                $sql .= ' where id='.$swapRow['id'];
                $sql = Db::execute($sql);
                if (!$sql)
                    break;
                $sql = 'update bg_type set sort='.$swapRow['sort'];
                $sql .= ' where id='.$id;
                break;
            default:
                return json_return('非法操作!');
        }

        $ret = ($sql !== 0) ? Db::execute($sql) : $sql;

        if (!$ret)
            return json_return($txt.'失败!');
        return json_return_refresh($txt.'成功!', $data_id, false);
    }

    //类型数据列表的数据获取及模板渲染
    private function _datalist($pid, $name, $data_id = "datalist", $size = null, $roll = null)
    {
        session($data_id.'.pid', $pid);
        session($data_id.'.typename', $name);

        $list = \DataList::obj('bg_type', $data_id)
            // ->where('pid='.$pid)->order('stick desc, mtime desc')
            ->where('pid='.$pid)->order('sort')
            ->fetch($size, $roll);
        $this->assign('name', $name);
        $this->assign('list', $list);
        return $this->fetch('type/datalist');
    }

    //子类型管理
    public function subType($pid, $name)
    {
        $data_id = __FUNCTION__.$pid;

        $this->assign('close_top_page', true);
        $data = $this->_datalist($pid, $name, $data_id, 1, 5);

        if (is_json())
            return json_return_data($data);

        $this->assign('html', $data);
        return view();
    }

    //主页面类型管理
    public function datalist($pid = 0, $name = "顶级类型")
    {
        // $data = $this->_datalist($pid, $name, 'datalist', 1, 5);
        $data = $this->_datalist($pid, $name);

        return is_json() ? json_return_data($data) : $data;
    }
}
